package log

import (
	"fmt"
	"gitee.com/yaodae/server-lib-go/config"
	rotateLogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"path/filepath"
	"time"
)

var (
	Log *logrus.Entry
)

func InitLog() error {
	// 加载日志配置
	if logLoad() {
		// 日志加载正常，可以继续向下进行
		return nil
	} else {
		return fmt.Errorf("发生了一个致命错误，程序结束 \n")
	}
}

func initLogger() *logrus.Logger {
	lkLog := logrus.New()
	lkLog.Formatter = new(logrus.TextFormatter)
	lkLog.Level = logrus.DebugLevel
	return lkLog
}

func logLoad() bool {
	lkLog := initLogger()
	Path, _ := filepath.Abs("")
	Path += "/logs"
	Path += "/" + config.SysConfig.ServiceName + ".log"
	writer, _ := rotateLogs.New(
		Path+".%Y%m%d%H%M",
		rotateLogs.WithLinkName(Path),
		rotateLogs.WithMaxAge(time.Duration(48)*time.Hour),
		rotateLogs.WithRotationTime(time.Duration(1)*time.Hour),
	)
	lkLog.SetOutput(writer)
	Log = lkLog.WithFields(logrus.Fields{
		"source": config.SysConfig.ServiceName,
	})
	return true
}

func Fatal(format ...interface{}) {
	Log.Fatal(format...)
}

func FatalF(format string, args ...interface{}) {
	Log.Fatalf(format, args...)
}
func FatalLn(args ...interface{}) {
	Log.Fatalln(args...)
}

func Debug(args ...interface{}) {
	Log.Debug(args...)
}

func DebugF(format string, args ...interface{}) {
	Log.Debugf(format, args...)
}
func DebugLn(args ...interface{}) {
	Log.Debugln(args...)
}

func Error(args ...interface{}) {
	Log.Error(args...)
}

func ErrorF(format string, args ...interface{}) {
	Log.Errorf(format, args...)
}

func ErrorLn(args ...interface{}) {
	Log.Errorln(args...)
}

func Info(args ...interface{}) {
	Log.Info(args...)
}

func InfoF(format string, args ...interface{}) {
	Log.Infof(format, args...)
}
func InfoLn(args ...interface{}) {
	Log.Infoln(args...)
}

func Warn(args ...interface{}) {
	Log.Warn(args...)
}

func WarnF(format string, args ...interface{}) {
	Log.Warnf(format, args...)
}

func WarnLn(args ...interface{}) {
	Log.Warnln(args...)
}
